package com.contest.ws;


import com.contest.util.DateUtil;
import com.contest.util.RandomUtil;
import com.contest.util.WsNeed;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaoleilu.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.*;
import redis.clients.jedis.Jedis;

import java.io.IOException;
import java.util.*;

public class WsPushGamingDataForKing implements WebSocketHandler {
    private static Map<String, String> data = new HashMap<String, String>();
    private ObjectMapper json = new ObjectMapper();
    private static String user;
    private static Map<String, WebSocketSession> sessions = Collections.synchronizedMap(new HashMap<String, WebSocketSession>());

    Jedis redis = new Jedis("120.79.198.159", 6379);

    @Override
    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
        WsNeed wsNeed = WsNeed.getInstance();
        user = webSocketSession.getAttributes().get("flag").toString();
        WebSocketSession session = sessions.get(user);
        if (session == null) {
            session = webSocketSession;

        } else {
            session.sendMessage(new TextMessage(JSONUtil.toJsonStr(data)));
        }
        sessions.put(user, session);

    }

    @Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
        String flag = webSocketMessage.getPayload().toString();
        user = webSocketSession.getAttributes().get("flag").toString();
        Map<String, String> temp = RandomUtil.king();
        Set<String> keys = temp.keySet();
        for (String key : keys) {
            redis.hset("王者荣耀", key, temp.get(key));
            redis.expire("王者荣耀", DateUtil.getTodayTimeDifference());
        }

        if (user != null && user.length() > 0 && "1".equals(user)) {
            WebSocketSession session = sessions.get(user);
            if (session.isOpen()) {
                try {
                    session.sendMessage(new TextMessage(JSONUtil.toJsonStr(temp)));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            data.putAll(temp);
        }
    }

    @Override
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {

    }

    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
        String user = webSocketSession.getAttributes().get("flag").toString();
        WebSocketSession socketSessions = sessions.get(user);
        if (socketSessions != null) {
            socketSessions.close();
        }

    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
